import { createContext, useContext, useEffect, useState } from "react";

type User = {
  id: string;
  name: string;
};

type AuthContextType = {
  user: User | null;
  isLoading: boolean;
  login: (id: string, name: string) => Promise<void>;
  logout: () => void;
};

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  useEffect(() => {
    const init = async () => {
      await new Promise((res) => setTimeout(res, 500));
      setUser(null); //初始化未登录
      setIsLoading(false);
    };
    init();
  }, []);

  const login = async (id: string, name: string) => {
    //模拟登录流程
    await new Promise((res) => setTimeout(res, 500));
    setUser({ id: "1", name: "Tony" });
  };

  const logout = () => {
    setUser(null);
  };

  return (
    <AuthContext.Provider value={{ user, isLoading, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

//封装自定义hook， 方便调用
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error("useAuth must be used within AuthProvider")
  }
  return context;
}
